package com.gitee.genshin.analyse.data.db;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.db.Db;
import cn.hutool.db.ds.simple.SimpleDataSource;
import cn.hutool.log.Log;
import com.gitee.genshin.analyse.Main;

import java.io.File;
import java.sql.SQLException;

/**
 * @author hongda.li.dlmu@qq.com 2022/7/13 9:16
 */
public class DatabaseSource {
    private DatabaseSource() {
    }

    /**
     * 数据库初始脚本
     */
    private static final String[] SQL_PATH = {"init-data.sql", "init-role.sql", "init-material.sql"};
    /**
     * 数据库驱动类名
     */
    private static final String DRIVER = "org.sqlite.JDBC";
    /**
     * 数据库链接URL前缀
     */
    private static final String URL_PREFIX = "jdbc:sqlite:";
    /**
     * 数据库存储路径
     */
    private static final String DATABASE_PATH = Main.CONFIG.getStr("data.path");
    private static final SimpleDataSource simpleDataSource;

    static {
        simpleDataSource = new SimpleDataSource(URL_PREFIX + DATABASE_PATH, "", "", DRIVER);
        initCheck();
    }

    public static SimpleDataSource getDataSource() {
        return DatabaseSource.simpleDataSource;
    }

    /**
     * 初始化数据库检查
     */
    private static void initCheck() {
        File file = new File(DATABASE_PATH);
        if (file.exists()) {
            return;
        }
        Log.get().warn("数据库文件不存在！系统将自动创建");
        String sql;
        for (String sqlPath : SQL_PATH) {
            sql = ResourceUtil.readUtf8Str(sqlPath);
            Log.get().info(sql);
            try {
                Db.use(getDataSource()).execute(sql);
            } catch (SQLException e) {
                Log.get().error("数据库初始化错误[{}][{}]", sql, e.getMessage());
                throw new RuntimeException(e);
            }
        }
        Log.get().info("数据库初始化成功");
    }
}
